package zy.service.index.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;

import zy.dao.index.IndexDAO;
import zy.dao.sys.sqb.SqbDAO;
import zy.entity.sell.cashier.T_Sell_Cashier;
import zy.entity.sell.cashier.T_Sell_Cashier_Set;
import zy.entity.sell.set.T_Sell_Set;
import zy.entity.sys.sqb.T_Sys_Sqb;
import zy.service.index.IndexService;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.HttpProxy;
import zy.util.StringUtil;
@Service
public class IndexServiceImpl implements IndexService{
	@Resource
	private IndexDAO indexDAO;
	@Resource
	private SqbDAO sqbDAO;
	@Transactional
	@Override
	public void login(Map<String, Object> paramMap) {
		//1.登录内容
		indexDAO.login(paramMap);
		T_Sell_Cashier cashier = (T_Sell_Cashier)paramMap.get(CommonUtil.KEY_CASHIER);
		
		List<T_Sell_Cashier_Set> setList = indexDAO.cashierSet(cashier);
		if(null != setList && setList.size() > 0){
			for(T_Sell_Cashier_Set set:setList){
				paramMap.put(set.getCs_key(), set.getCs_value());
			}
		}
		List<T_Sell_Set> shopList = indexDAO.shopSet(cashier);
		if(null != shopList && shopList.size() > 0){
			for(T_Sell_Set set:shopList){
				paramMap.put(set.getSt_key(), set.getSt_value());
			}
		}
		
		//2.查询店铺的设置
		//3.安全盾的验证
		
		//收钱吧签到
		checkin_sqb(cashier);
	}
	
	private void checkin_sqb(T_Sell_Cashier cashier){
		if(cashier == null || cashier.getSqb() == null){//未配置收钱吧
			return;
		}
		final T_Sys_Sqb sqb = cashier.getSqb();
		if (StringUtil.isEmpty(sqb.getSqb_terminal_sn()) || StringUtil.isEmpty(sqb.getSqb_terminal_key())) {//未激活
			return;
		}
		String lastcheckin = sqb.getSqb_checkin_time();
		if(StringUtil.isEmpty(lastcheckin)){
			lastcheckin = sqb.getSqb_activate_time();
		}
		long days = DateUtil.getDaysMinusBetween(lastcheckin,DateUtil.getYearMonthDate());
		if (days <= 0) {//当天已签到
			return;
		}
		new Thread(new Runnable() {
			@Override
			public void run() {
				HttpProxy hp = new HttpProxy(CommonUtil.SQB_API_DOMAIN);
				JSONObject terminal = hp.checkin(sqb.getSqb_terminal_sn(), sqb.getSqb_terminal_key(),sqb.getSqb_device_id());
				if (terminal != null) {
					sqb.setSqb_terminal_key(terminal.getString("terminal_key"));
					sqb.setSqb_checkin_time(DateUtil.getCurrentTime());
					sqbDAO.update_checkin(sqb);
				}
			}
		}).start();
	}
	
	
	@Override
	public void editPass(Map<String, Object> paramMap) {
		indexDAO.editPass(paramMap);
	}

}
